import os
import sys
import time
import tkinter as tk
from tkinter import font
from tkinter import messagebox

import pystray
import ttkbootstrap as ttkb
from PIL import Image, ImageDraw
from ttkbootstrap.constants import *

from app.controller.main_controller import MainController
from app.view.base_view import get_views
from config.tk_desktop_toolset_param import version

menu_map = [
    ("file", "查看", True),
    ("ft_tool", "FT工具", True),
    ("dev_tool", "DEV工具", True),
    ("tool", "DEV工具", True),
    ("help", "帮助", True),
    ("home", "主页", True),
    ("setting", "设置", True),
    ("about", "关于", True),
]


class MainWindow(ttkb.Window):
    """主窗口类，包含菜单栏、内容区域和状态栏"""

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.title(f"DesktopToolset {version}")
        self.geometry("1200x800")
        self.minsize(600, 400)

        # 统一菜单字体设置
        self.menu_font_size = 10
        # 创建统一的菜单字体配置，使用系统默认字体族
        self.menu_font = font.Font(size=self.menu_font_size)
        self.option_add("*Menu.font", self.menu_font)

        # 创建状态栏变量
        self.status_var = tk.StringVar(value="就绪")
        self.time_var = tk.StringVar()
        self.progress_var = tk.DoubleVar(value=0)

        # 托盘图标相关
        self.tray_icon = None
        self.running_in_background = False

        self.view_model = get_views()
        # 创建菜单栏
        self._create_top_menu(self.view_model)

        # 创建内容区域
        self._create_content_frame()

        # 创建状态栏
        self._create_status_bar()

        # 初始化控制器
        self.controller = MainController(self, self.view_model)

        # 窗口关闭事件
        # self.protocol("WM_DELETE_WINDOW", self.minimize_to_tray)

    def _create_top_menu(self, view_model):
        """创建菜单栏 - 确保所有层级菜单使用相同字体"""
        # 主菜单
        self.top_menu = ttkb.Menu(self, font=self.menu_font)
        # 按照分类自动添加菜单 在打包环节会出现问题
        # #
        # for item in menu_map:
        #     menu = ttkb.Menu(self.top_menu, tearoff=0, font=self.menu_font)
        #     # 添加二级菜单
        #     for view in view_model:
        #         annotations = AnnotationHelper.get_annotations(view)
        #         for an_type, ann in annotations.items():
        #             if ann.category == item[0]:
        #                 menu.add_command(label=f"{ann.name}",
        #                                  command=lambda view_name=str(f"{view.__name__}"): self.controller.show_view(
        #                                      view_name),
        #                                  font=self.menu_font)
        #     self.top_menu.add_cascade(label=item[1], menu=menu, font=self.menu_font)

        # 文件菜单（一级菜单）
        file_menu = ttkb.Menu(self.top_menu, tearoff=0, font=self.menu_font)
        file_menu.add_command(label="首页", command=lambda: self.controller.show_view("home"), font=self.menu_font)
        file_menu.add_command(label="查看文件", command=lambda: self.controller.show_view("file_sys"),
                              font=self.menu_font)
        file_menu.add_command(label="文本查看", command=lambda: self.controller.show_view("file_text"),
                              font=self.menu_font)
        file_menu.add_command(label="BinaryView", command=lambda: self.controller.show_view("file_binary"),
                              font=self.menu_font)

        # file_menu.add_command(label="PDF查看", command=lambda: self.controller.show_view("file_pdf"),
        #                       font=self.menu_font)
        # file_menu.add_command(label="DXF查看", command=lambda: self.controller.show_view("file_cad"),
        #                       font=self.menu_font)

        file_menu.add_separator()
        file_menu.add_command(label="退出", command=self.quit, font=self.menu_font)
        self.top_menu.add_cascade(label="查看", menu=file_menu, font=self.menu_font)

        # 工具菜单（一级菜单）
        tool_menu = ttkb.Menu(self.top_menu, tearoff=0, font=self.menu_font)
        tool_menu.add_command(label="网络调试", command=lambda: self.controller.show_view("net"),
                              font=self.menu_font)
        tool_menu.add_command(label="串口调试", command=lambda: self.controller.show_view("serial"),
                              font=self.menu_font)
        tool_menu.add_command(label="数据校验", command=lambda: self.controller.show_view("check_sum"),
                              font=self.menu_font)
        tool_menu.add_command(label="网络测速", command=lambda: self.controller.show_view("net_speed"),
                              font=self.menu_font)
        # tool_menu.add_command(label="远程桌面", command=lambda: self.controller.show_view("remote_desktop"),
        #                       font=self.menu_font)
        # tool_menu.add_command(label="计算器", command=lambda: self.controller.show_view("calculate"),
        #                       font=self.menu_font)
        # tool_menu.add_command(label="3D", command=lambda: self.controller.show_view("3d"),
        #                       font=self.menu_font)
        tool_menu.add_command(label="API", command=lambda: self.controller.show_view("api"),
                              font=self.menu_font)
        tool_menu.add_command(label="Hex&Bin", command=lambda: self.controller.show_view("hex_bin"),
                              font=self.menu_font)
        tool_menu.add_command(label="Task", command=lambda: self.controller.show_view("task"),
                              font=self.menu_font)
        # tool_menu.add_command(label="网络文件传输", command=lambda: self.controller.show_view("tcp_file_transfer"),
        #                       font=self.menu_font)
        # tool_menu.add_command(label="图片格式转换", command=lambda: self.controller.show_view("img_convertor"),
        #                       font=self.menu_font)
        # tool_menu.add_command(label="图片编辑", command=lambda: self.controller.show_view("img_edit"),
        #                       font=self.menu_font)
        tool_menu.add_command(label="MAC生成", command=lambda: self.controller.show_view("mac_generator"),
                              font=self.menu_font)
        self.top_menu.add_cascade(label="工具", menu=tool_menu, font=self.menu_font)

        # FT工具菜单（一级菜单）
        ft_tool_menu = ttkb.Menu(self.top_menu, tearoff=0, font=self.menu_font)
        ft_tool_menu.add_command(label="Jlink", command=lambda: self.controller.show_view("ft_jlink"),
                                 font=self.menu_font)
        ft_tool_menu.add_command(label="HwAuFt", command=lambda: self.controller.show_view("ft_serial_hw_au"),
                                 font=self.menu_font)
        ft_tool_menu.add_command(label="TcpBleHwAuFt", command=lambda: self.controller.show_view("ft_tcp_ble_hw_au"),
                                 font=self.menu_font)
        ft_tool_menu.add_command(label="DFU Serial", command=lambda: self.controller.show_view("ft_serial_update"),
                                 font=self.menu_font)
        ft_tool_menu.add_command(label="DFU Serial Ymodem",
                                 command=lambda: self.controller.show_view("ft_serial_ymodem_update"),
                                 font=self.menu_font)
        ft_tool_menu.add_command(label="DFU TCP", command=lambda: self.controller.show_view("ft_tcp_update"),
                                 font=self.menu_font)
        # ft_tool_menu.add_command(label="SerialParamSet",
        #                          command=lambda: self.controller.show_view("ft_serial_param_set"),
        #                          font=self.menu_font)
        ft_tool_menu.add_command(label="AuCardConfig",
                                 command=lambda: self.controller.show_view("ft_au_card_config"),
                                 font=self.menu_font)
        ft_tool_menu.add_command(label="AuCardCmdConfig",
                                 command=lambda: self.controller.show_view("ft_au_card_cmd_config"),
                                 font=self.menu_font)
        ft_tool_menu.add_command(label="AuSnPrint",
                                 command=lambda: self.controller.show_view("ft_au_sn_print"),
                                 font=self.menu_font)
        ft_tool_menu.add_command(label="UdpConfig",
                                 command=lambda: self.controller.show_view("ft_udp_config"),
                                 font=self.menu_font)
        self.top_menu.add_cascade(label="FT工具", menu=ft_tool_menu, font=self.menu_font)

        # DEV工具（一级菜单）
        dev_tool_menu = ttkb.Menu(self.top_menu, tearoff=0, font=self.menu_font)
        dev_tool_menu.add_command(label="PyExecutor", command=lambda: self.controller.show_view("py_code"),
                                  font=self.menu_font)
        # dev_tool_menu.add_command(label="SSH", command=lambda: self.controller.show_view("ssh"),
        #                           font=self.menu_font)
        dev_tool_menu.add_command(label="BLE Connector", command=lambda: self.controller.show_view("ble_connector"),
                                  font=self.menu_font)
        dev_tool_menu.add_command(label="AbinGenerator", command=lambda: self.controller.show_view("abin"),
                                  font=self.menu_font)
        dev_tool_menu.add_command(label="Serial CMD", command=lambda: self.controller.show_view("serial_cmd"),
                                  font=self.menu_font)
        dev_tool_menu.add_command(label="Lib Parser", command=lambda: self.controller.show_view("lib_parser"),
                                  font=self.menu_font)
        self.top_menu.add_cascade(label="DEV工具", menu=dev_tool_menu, font=self.menu_font)

        # # MUSE（一级菜单）
        # muse_menu = ttkb.Menu(self.top_menu, tearoff=0, font=self.menu_font)
        # muse_menu.add_command(label="Music", command=lambda: self.controller.show_view("music"),
        #                       font=self.menu_font)
        # muse_menu.add_command(label="Video", command=lambda: self.controller.show_view("video"),
        #                       font=self.menu_font)
        # self.top_menu.add_cascade(label="MUSE", menu=muse_menu, font=self.menu_font)

        # 系统设置（一级菜单）
        view_menu = ttkb.Menu(self.top_menu, tearoff=0, font=self.menu_font)
        view_menu.add_command(label="系统设置", command=lambda: self.controller.show_view("settings"),
                              font=self.menu_font)
        self.top_menu.add_cascade(label="设置", menu=view_menu, font=self.menu_font)

        # 帮助菜单（一级菜单）
        help_menu = ttkb.Menu(self.top_menu, tearoff=0, font=self.menu_font)
        # help_menu.add_command(label="用户手册", command=self._show_help, font=self.menu_font)
        help_menu.add_command(label="关于", command=lambda: self.controller.show_view("about"), font=self.menu_font)
        self.top_menu.add_cascade(label="帮助", menu=help_menu, font=self.menu_font)

        # 设置菜单栏
        self.config(menu=self.top_menu)

    def update_menu_font(self, size):
        """更新所有菜单（包括一级和二级）的字体大小"""
        self.menu_font_size = size
        # 更新字体配置
        self.menu_font.configure(size=size)
        # 重新创建菜单以应用新字体设置
        self._create_top_menu()

    def _create_content_frame(self):
        """创建内容区域"""
        self.content_frame = ttkb.Frame(self)
        self.content_frame.pack(fill=BOTH, expand=True, padx=10, pady=5)

    def _create_status_bar(self):
        """创建状态栏"""

        # 状态提示栏
        self.status_bar = ttkb.Label(self, textvariable=self.status_var, relief=FLAT, borderwidth=0, anchor=W)

        # 进度条
        self.progress_bar = ttkb.Progressbar(self, variable=self.progress_var, length=100, mode='determinate')

        # 时间标签
        time_label = ttkb.Label(self, textvariable=self.time_var)

        # 布局状态栏组件
        self.status_bar.pack(side=LEFT, fill=X, expand=True, padx=5, pady=2)
        self.progress_bar.pack(side=LEFT, padx=5)
        time_label.pack(side=RIGHT, padx=10, pady=2)

    def _show_help(self):
        messagebox.showinfo("帮助", "用户手册内容...")

    def _simulate_progress(self):
        """模拟进度条更新"""
        for i in range(101):
            self.progress_var.set(i)
            time.sleep(0.02)
        self.progress_var.set(0)

    def create_tray_icon(self):
        """创建托盘图标"""
        # 如果没有提供图标文件，创建一个简单的默认图标
        try:
            # 尝试加载自定义图标
            icon_path = self.get_resource_path("resources/img/desktop_toolset_256_256.ico")
            image = Image.open(icon_path)
        except:
            # 创建默认图标
            image = Image.new('RGB', (64, 64), color=(73, 109, 137))
            d = ImageDraw.Draw(image)
            d.text((10, 20), "ST", fill=(255, 255, 255), font_size=24)

        # 创建托盘菜单
        menu = pystray.Menu(
            pystray.MenuItem("显示窗口", self.show_window),
            pystray.MenuItem("退出", self.quit_app)
        )

        # 创建托盘图标
        self.tray_icon = pystray.Icon("系统托盘应用", image, "系统托盘应用", menu)
        # self.tray_icon.on_click = self.on_tray_click  # 绑定单击/双击事件
        # 启动托盘图标线程
        self.tray_icon.run_detached()

    # def on_tray_click(self, icon, event):
    #     """处理托盘图标点击事件"""
    #     # 检测双击事件
    #     if event == pystray.MouseEvent.DOUBLE_CLICK:
    #         if self.running_in_background:
    #             self.show_window()
    #         else:
    #             self.minimize_to_tray()
    def minimize_to_tray(self):
        """最小化到系统托盘"""
        if not self.tray_icon:
            self.create_tray_icon()

        self.running_in_background = True
        self.withdraw()  # 隐藏窗口
        # messagebox.showinfo("提示", "程序已最小化到系统托盘")

    def show_window(self):
        """从托盘显示窗口"""
        self.deiconify()  # 显示窗口
        self.running_in_background = False

    def quit_app(self):
        """退出应用程序"""
        if self.tray_icon:
            self.tray_icon.stop()
        self.destroy()
        sys.exit(0)

    def get_resource_path(self, relative_path):
        """获取资源文件路径，适用于开发和打包后"""
        try:
            # PyInstaller创建临时文件夹,将路径存储在_MEIPASS中
            base_path = sys._MEIPASS
        except Exception:
            base_path = os.path.abspath(".")

        return os.path.join(base_path, relative_path)
